package com.example.learn.juc;

import ch.qos.logback.core.util.TimeUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchExample1 {
    public static final int gradeNum = 6;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newScheduledThreadPool(gradeNum);
        final CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < gradeNum; i++) {
            int gradeName = i + 1;
            exec.submit(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    wait(gradeName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        TimeUnit.SECONDS.sleep(3);
        System.out.println("通知、通知，请全体同学速来操场集合.....");
        latch.countDown();

        exec.shutdown();
    }

    private static void wait(int gradeName) throws Exception {
        TimeUnit.MILLISECONDS.sleep((int) Math.random() * 1000);
        System.out.println(gradeName + "年级所有同学到达操场");
    }
}
